package com.chun.learning.analyzation.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.chun.learning.analyzation.mapper.AnalyzeMapper;
import com.chun.learning.analyzation.po.ClassRepoListItem;
import com.chun.learning.analyzation.po.StuRepoListItem;
import com.chun.learning.analyzation.po.StudentUseReport;
import com.chun.learning.analyzation.service.AnalyzeService;
import com.czy.learning.questionnature.mapper.QuestionNatureMapper;
import com.lin.learning.questionmanagement.mapper.QuestionMapper;
import com.lin.learning.questionmanagement.service.QuestionService;
import com.ni.learning.exam.controller.AnswerSheetController;
import com.ni.learning.exam.mapper.AnswerSheetMapper;
import com.ni.learning.exam.mapper.ExamMapper;
import com.our.learning.infrastructure.po.*;
import com.our.learning.infrastructure.pojo.Response;
import com.our.learning.infrastructure.pojo.ResponseResult;
import com.studentmanagement.mapper.ClassMapper;
import com.studentmanagement.mapper.StudentMapper;
import com.studentmanagement.po.StudentPO;
import com.studentmanagement.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AnalyzeServiceImpl extends ServiceImpl<AnalyzeMapper, WrongQuestionReport> implements AnalyzeService {

    @Autowired
    private AnalyzeMapper analyzeMapper;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private QuestionNatureMapper questionNatureMapper;

    @Autowired
    private AnswerSheetController answerSheetController;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private StudentService studentService;

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private AnswerSheetMapper answerSheetMapper;

    @Autowired
    private ClassMapper classMapper;


    @Override
    public ResponseResult generateWrongReport(Integer stuid, Integer examid) {
        //根据examid获取paperid examName
        LambdaQueryWrapper<Exam> examLambdaQueryWrapper=new LambdaQueryWrapper<>();
        examLambdaQueryWrapper.select(Exam::getPaperId,Exam::getName).eq(Exam::getId,examid);
        Integer paperid = examMapper.selectOne(examLambdaQueryWrapper).getPaperId();
        String examName = examMapper.selectOne(examLambdaQueryWrapper).getName();

        if(paperid==null){
            return ResponseResult.errorResult(508,"该学生没有参加这场考试");
        }
        //通过学生和试卷id找到错题列表
        List wrongQuestionidList = answerSheetController.getIncorrectIds(stuid,paperid);
        //通过错题id找到相应错题
        String questionList="";
        //拼接成错题idlist用于存入数据库
        for(int i=0;i<wrongQuestionidList.size();i++){
            String id=wrongQuestionidList.get(i).toString();
            if (i<wrongQuestionidList.size()-1){
                questionList=questionList+id+',';
            }else {
                questionList=questionList+id;
            }


        }

        if("".equals(questionList)){
            return ResponseResult.okResult(510,"该学生没有错题");
        }


        //获取student信息
        List<StudentPO> list= studentService.studentListLocal(stuid,null);
        StudentPO studentPO = list.get(0);

        //组装错题报告
        WrongQuestionReport wrongQuestionReport=new WrongQuestionReport();
        wrongQuestionReport.setClassId(studentPO.getClassId());
        wrongQuestionReport.setPaperId(paperid);
        wrongQuestionReport.setStudentId(stuid);
        wrongQuestionReport.setIdList(questionList);
        wrongQuestionReport.setExamId(examid);

        //查询数据库是否已经有错题报告
        LambdaQueryWrapper<WrongQuestionReport> wrongQuestionReportLambdaQueryWrapper=new LambdaQueryWrapper<>();
        wrongQuestionReportLambdaQueryWrapper.eq(WrongQuestionReport::getStudentId,stuid).eq(WrongQuestionReport::getPaperId,paperid).eq(WrongQuestionReport::getExamId,examid);
        //WrongQuestionReport wrongQuestionReport1=getOne(wrongQuestionReportLambdaQueryWrapper);
        if (getOne(wrongQuestionReportLambdaQueryWrapper)!=null){
            return ResponseResult.errorResult(509,"该学生已生成过该试卷错题报告，请勿重复生成");
        }

        //保存报告
        save(wrongQuestionReport);

        //把获取到的数据组成前端的错题报告
        List<Question> questionList1=questionMapper.selectBatchIds(wrongQuestionidList);
        List<QuestionNature> questionNatureList=questionNatureMapper.selectBatchIds(wrongQuestionidList);
        List<ReportItem> reportItemList=new ArrayList<>(questionList1.size());
        for(int i=0;i<questionList1.size();i++){
            ReportItem reportItem=new ReportItem();
            reportItem.setQuestion(questionList1.get(i));
            reportItem.setAnswer(questionNatureList.get(i).getAnswer());
            reportItem.setDifficulty(questionNatureList.get(i).getDifficulty().toString());
            reportItem.setKnowledge(questionNatureList.get(i).getKnowledge());
            reportItemList.add(i,reportItem);
        }

        //带上学生名字 考试名字 试卷id 错题内容返回
        StudentUseReport studentUseReport=new StudentUseReport(stuid,studentPO.getName(),paperid,reportItemList,examName,examid,null);

        return ResponseResult.okResult(studentUseReport);
    }


    public StudentUseReport generateWrongReportLocal(Integer stuid, Integer paperid,Integer examid,String link) {

        LambdaQueryWrapper<Exam> examLambdaQueryWrapper=new LambdaQueryWrapper<>();
        examLambdaQueryWrapper.select(Exam::getName).eq(Exam::getId,examid);
        String examName = examMapper.selectOne(examLambdaQueryWrapper).getName();
        //通过学生和试卷id找到错题列表
        List wrongQuestionidList = answerSheetController.getIncorrectIds(stuid,paperid);
        //通过错题id找到相应错题
        String questionList="";

        for(int i=0;i<wrongQuestionidList.size();i++){
            String id=wrongQuestionidList.get(i).toString();
            if (i<wrongQuestionidList.size()-1){
                questionList=questionList+id+',';
            }else {
                questionList=questionList+id;
            }


        }
        //组装学生数据
        List<StudentPO> list= studentService.studentListLocal(stuid,null);
        StudentPO studentPO = list.get(0);
        WrongQuestionReport wrongQuestionReport=new WrongQuestionReport();
        wrongQuestionReport.setClassId(studentPO.getClassId());
        wrongQuestionReport.setPaperId(paperid);
        wrongQuestionReport.setStudentId(stuid);
        wrongQuestionReport.setIdList(questionList);

        //把获取到的数据组成错题报告
        List<Question> questionList1=questionMapper.selectBatchIds(wrongQuestionidList);
        List<QuestionNature> questionNatureList=questionNatureMapper.selectBatchIds(wrongQuestionidList);
        List<ReportItem> reportItemList=new ArrayList<>(questionList1.size());
        for(int i=0;i<questionList1.size();i++){
            ReportItem reportItem=new ReportItem();
            reportItem.setQuestion(questionList1.get(i));
            reportItem.setAnswer(questionNatureList.get(i).getAnswer());
            reportItem.setDifficulty(questionNatureList.get(i).getDifficulty().toString());
            reportItem.setKnowledge(questionNatureList.get(i).getKnowledge());
            reportItemList.add(i,reportItem);
        }

        StudentUseReport studentUseReport=new StudentUseReport(stuid,studentPO.getName(),paperid,reportItemList,examName,examid,link);

        return studentUseReport;
    }

    @Override
    public ResponseResult getStudentAllReports(String stuid) {
        if(stuid==""){
            //空值时默认获取所有报告，通过id>0的条件来进行sql的查询
            LambdaQueryWrapper<WrongQuestionReport> lambdaQueryWrapper=new LambdaQueryWrapper();
            lambdaQueryWrapper.ge(WrongQuestionReport::getId,0);
            List<WrongQuestionReport> wrongQuestionReports = analyzeMapper.selectList(lambdaQueryWrapper);
            List<String> links = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getLink).collect(Collectors.toList());
            List<Integer> collect4 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getPaperId).collect(Collectors.toList());
            List<Integer> collect = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getStudentId).collect(Collectors.toList());
            List<String> collect1 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getIdList).collect(Collectors.toList());
            List<Integer> collect2 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getPaperId).collect(Collectors.toList());
            List<Integer> collect3 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getExamId).collect(Collectors.toList());
            List<StudentUseReport> studentUseReports=new ArrayList<>(links.size());
            for(int i=0;i<collect.size();i++){
                //通过学生和试卷id找到错题列表
                StudentUseReport studentUseReport = generateWrongReportLocal(collect.get(i),collect2.get(i),collect3.get(i),links.get(i));
                studentUseReports.add(studentUseReport);
            }

            return ResponseResult.okResult(studentUseReports);
        }
/*        List<String> allReportsByStudentId = analyzeMapper.getAllReportsByStudentId(stuid);
        return ResponseResult.okResult(allReportsByStudentId);*/
        LambdaQueryWrapper<WrongQuestionReport> lambdaQueryWrapper=new LambdaQueryWrapper();
        //通过搜索stuid获取所有该学生的错题报告
        lambdaQueryWrapper.select(WrongQuestionReport::getStudentId,WrongQuestionReport::getLink,WrongQuestionReport::getPaperId,WrongQuestionReport::getClassId,WrongQuestionReport::getExamId).eq(WrongQuestionReport::getStudentId,stuid);
        List<String> links = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getLink).collect(Collectors.toList());
        List<Integer> collect4 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getPaperId).collect(Collectors.toList());
        List<Integer> collect = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getStudentId).collect(Collectors.toList());
        List<String> collect1 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getIdList).collect(Collectors.toList());
        List<Integer> collect2 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getPaperId).collect(Collectors.toList());
        List<Integer> collect3 = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getExamId).collect(Collectors.toList());
        List<StuRepoListItem> list=new ArrayList<>(collect.size());

        List<StudentUseReport> studentUseReports=new ArrayList<>(links.size());

        for(int i=0;i<collect.size();i++){

            //通过学生和试卷id找到错题列表
           /* List wrongQuestionidList = answerSheetController.getIncorrectIds(collect.get(i),collect2.get(i));
            //通过错题id找到相应错题
            String questionList="";

            for(int j=0;i<wrongQuestionidList.size();j++){
                String id=wrongQuestionidList.get(j).toString();
                if (i<wrongQuestionidList.size()-1){
                    questionList=questionList+id+',';
                }else {
                    questionList=questionList+id;
                }
            }
            List<StudentPO> list1= studentService.studentListLocal(collect.get(i),null);
            StudentPO studentPO = list1.get(0);
            WrongQuestionReport wrongQuestionReport=new WrongQuestionReport();
            wrongQuestionReport.setClassId(studentPO.getClassId());
            wrongQuestionReport.setPaperId(collect2.get(i));
            wrongQuestionReport.setStudentId(collect.get(i));
            wrongQuestionReport.setIdList(questionList);

            List<Question> questionList1=questionMapper.selectBatchIds(wrongQuestionidList);
            List<QuestionNature> questionNatureList=questionNatureMapper.selectBatchIds(wrongQuestionidList);
            List<ReportItem> reportItemList=new ArrayList<>(questionList1.size());
            for(int k=0;i<questionList1.size();k++){
                ReportItem reportItem=new ReportItem();
                reportItem.setQuestion(questionList1.get(k));
                reportItem.setAnswer(questionNatureList.get(k).getAnswer());
                reportItem.setDifficulty(questionNatureList.get(k).getDifficulty().toString());
                reportItem.setKnowledge(questionNatureList.get(k).getKnowledge());
                reportItemList.add(k,reportItem);
            }

            StudentUseReport studentUseReport=new StudentUseReport(studentPO.getName(),reportItemList);

            StuRepoListItem item=new StuRepoListItem();
            item.setName(studentService.studentListLocal(collect.get(i),collect3.get(i)).get(0).getName());
            item.setId(collect.get(i));
            item.setLink(links.get(i));
            item.setWrongQuestionReport(wrongQuestionReport);
            list.add(i,item);*/
            StudentUseReport studentUseReport = generateWrongReportLocal(Integer.valueOf(stuid),collect2.get(i),collect3.get(i),links.get(i));
            studentUseReports.add(studentUseReport);
        }

        return ResponseResult.okResult(studentUseReports);
    }

    @Override
    public ResponseResult getWrongReport(Integer stuid) {
/*        LambdaQueryWrapper<WrongQuestionReport> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(WrongQuestionReport::getStudentId,stuid).eq(WrongQuestionReport::getPaperId,paperid);
        WrongQuestionReport report = getOne(lambdaQueryWrapper);
        String wrongQuestionIdList= report.getWrongIdList();
        String[] split = wrongQuestionIdList.split(",");
        List<String> id = Arrays.asList(split);
        //把获取到的数据组成错题报告
        List<Question> questionList1=questionMapper.selectBatchIds(id);
        List<QuestionNature> questionNatureList=questionNatureMapper.selectBatchIds(id);
        List<ReportItem> reportItemList=new ArrayList<>();

        for(int i=0;i<questionList1.size();i++){
            ReportItem reportItem=new ReportItem();
            reportItem.setQuestion(questionList1.get(i));
            reportItem.setAnswer(questionNatureList.get(i).getAnswer());
            reportItem.setDifficulty(questionNatureList.get(i).getDifficulty().toString());
            reportItem.setKnowledge(questionNatureList.get(i).getKnowledge());
            reportItemList.add(i,reportItem);
        }
        List<StudentPO> list= studentService.studentListLocal(stuid,null);
        StudentPO studentPO = list.get(0);
        StudentUseReport studentUseReport=new StudentUseReport(studentPO.getName(),reportItemList);*/
        List<WrongQuestionReport> wrongQuestionReports = analyzeMapper.selectList(new LambdaQueryWrapper<WrongQuestionReport>()
                .select(WrongQuestionReport::getStudentId,WrongQuestionReport::getPaperId)
                .eq(WrongQuestionReport::getStudentId, stuid));

        return ResponseResult.okResult(wrongQuestionReports.stream().map(WrongQuestionReport::getPaperId).collect(Collectors.toList()));
    }

    @Override
    public ResponseResult getClassReports(Integer classid) {
        //读取错误报告里的不同字段，将他们组成list
        LambdaQueryWrapper<WrongQuestionReport> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.select(WrongQuestionReport::getStudentId,WrongQuestionReport::getLink,WrongQuestionReport::getPaperId).eq(WrongQuestionReport::getClassId,classid);
        List<String> links = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getLink).collect(Collectors.toList());
        List<Integer> papercollect = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getPaperId).collect(Collectors.toList());
        List<Integer> stucollect = analyzeMapper.selectList(lambdaQueryWrapper).stream().map(WrongQuestionReport::getStudentId).collect(Collectors.toList());
        List<ClassRepoListItem> list=new ArrayList<>(stucollect.size());

        //判断有无该class，没有就直接返回
        LambdaQueryWrapper<Clazz> clazzLambdaQueryWrapper=new LambdaQueryWrapper<>();
        clazzLambdaQueryWrapper.select(Clazz::getId).eq(Clazz::getId,classid);
        Clazz clazz = classMapper.selectOne(clazzLambdaQueryWrapper);
        if (clazz==null){
            return ResponseResult.okResult(list);
        }





        //合成班级所有人的所有错题报告
        for(int i=0;i<stucollect.size();i++){
            //每个学生根据学生id和试卷id获取考试id
            LambdaQueryWrapper<AnswerSheet> answerLambdaQueryWrapper=new LambdaQueryWrapper();
            answerLambdaQueryWrapper.select(AnswerSheet::getExamId).eq(AnswerSheet::getPaperId,papercollect.get(i)).eq(AnswerSheet::getStudentId,stucollect.get(i));
            Integer examId = answerSheetMapper.selectOne(answerLambdaQueryWrapper).getExamId();


            //每一个都设置成班级错题报告里的一个item
            ClassRepoListItem item=new ClassRepoListItem();
            item.setName(studentService.studentListLocal(stucollect.get(i),classid).get(0).getName());
            //获取某个学生某场考试的错题报告
            item.setStudentUseReport(getOneReport(stucollect.get(i),examId));
            item.setId(stucollect.get(i));
            //有链接就添加上去
            if (links.get(i)!=null){
                item.setLink(links.get(i));
            }
            list.add(i,item);
        }

        return ResponseResult.okResult(list);
    }

    @Override
    public ResponseResult getAdminReport() {

        return null;
    }

    @Override
    public ResponseResult deleteReport(Integer stuid, Integer examid) {
        LambdaQueryWrapper<WrongQuestionReport> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(WrongQuestionReport::getId).eq(WrongQuestionReport::getStudentId,stuid).eq(WrongQuestionReport::getExamId,examid);
        Integer id = analyzeMapper.selectOne(lambdaQueryWrapper).getId();
        analyzeMapper.deleteById(id);
        return ResponseResult.okResult();
    }


    public StudentUseReport getOneReport(Integer stuid,Integer examid) {

        //获取examName
        LambdaQueryWrapper<Exam> examLambdaQueryWrapper=new LambdaQueryWrapper<>();
        examLambdaQueryWrapper.select(Exam::getName).eq(Exam::getId,examid);
        String examName = examMapper.selectOne(examLambdaQueryWrapper).getName();

        //获取paperid
        LambdaQueryWrapper<Exam> paperLambdaQueryWrapper=new LambdaQueryWrapper<>();
        paperLambdaQueryWrapper.select(Exam::getPaperId).eq(Exam::getId,examid);
        Integer paperid = examMapper.selectOne(paperLambdaQueryWrapper).getPaperId();

        LambdaQueryWrapper<WrongQuestionReport> lambdaQueryWrapper=new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(WrongQuestionReport::getStudentId,stuid).eq(WrongQuestionReport::getPaperId,paperid).eq(WrongQuestionReport::getExamId,examid);
        WrongQuestionReport report = getOne(lambdaQueryWrapper);
        String wrongQuestionIdList= report.getIdList();
        String[] split = wrongQuestionIdList.split(",");
        List<String> id = Arrays.asList(split);
        //把获取到的数据组成错题报告
        List<Question> questionList1=questionMapper.selectBatchIds(id);
        List<QuestionNature> questionNatureList=questionNatureMapper.selectBatchIds(id);
        List<ReportItem> reportItemList=new ArrayList<>();

        //用循环组装错题item弄成错题list
        for(int i=0;i<questionList1.size();i++){
            ReportItem reportItem=new ReportItem();
            reportItem.setQuestion(questionList1.get(i));
            reportItem.setAnswer(questionNatureList.get(i).getAnswer());
            reportItem.setDifficulty(questionNatureList.get(i).getDifficulty().toString());
            reportItem.setKnowledge(questionNatureList.get(i).getKnowledge());
            reportItemList.add(i,reportItem);
        }
        //获取学生姓名
        List<StudentPO> list= studentService.studentListLocal(stuid,null);
        StudentPO studentPO = list.get(0);
        StudentUseReport studentUseReport=new StudentUseReport(stuid,studentPO.getName(),paperid,reportItemList,examName,examid,report.getLink());
        return studentUseReport;
    }
}
